package com.example.springboot.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.springboot.common.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.controller.dto.HandPaperDTO;
import com.example.springboot.controller.dto.PaperDTO;
import com.example.springboot.entity.PaperQuestion;
import com.example.springboot.entity.Question;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.service.IPaperQuestionService;
import com.example.springboot.service.IQuestionService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.example.springboot.service.IPaperService;
import com.example.springboot.entity.Paper;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wgc
 * @since 2023-10-04
 */
@RestController
@RequestMapping("/paper")
public class PaperController {

    @Resource
    private IPaperService paperService;

    @Resource
    private IQuestionService questionService;   //题库

    @Resource
    private IPaperQuestionService paperQuestionService;  // 组卷关联关系表

    //新增和修改
    @PostMapping
    public Result save(@RequestBody Paper paper) {  //@RequestBody接收前端数据
        return Result.success(paperService.saveOrUpdate(paper));
    }

    @PostMapping("/handPaper")
    public Result handPaper(@RequestBody HandPaperDTO handPaperDTO) {
         // 删除老的试卷
        UpdateWrapper<PaperQuestion> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("paper_id", handPaperDTO.getPaperId());
        paperQuestionService.remove(updateWrapper);

        if (CollUtil.isEmpty(handPaperDTO.getHandleQuestionIds())) {
            throw new ServiceException("-1", "题目数量不足");
        }
        List<Integer> handleQuestionIds = handPaperDTO.getHandleQuestionIds();
        List<PaperQuestion> list = new ArrayList<>();
        for (Integer handleQuestionId : handleQuestionIds) {
            PaperQuestion paperQuestion = new PaperQuestion();
            paperQuestion.setPaperId(handPaperDTO.getPaperId());
            paperQuestion.setQuestionId(handleQuestionId);
            list.add(paperQuestion);
        }
        paperQuestionService.saveBatch(list);
        return Result.success();
    }

    @PostMapping("/takePaper")
    public Result takePaper(@RequestBody PaperDTO paperDTO) {  //@RequestBody接收前端数据
        // 删除老的试卷
        UpdateWrapper<PaperQuestion> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("paper_id", paperDTO.getPaperId());
        paperQuestionService.remove(updateWrapper);

        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", paperDTO.getCourseId());
        // 根据课程id查出所有该课程的题目，然后再根据type去分
        List<Question> questionList = questionService.list(queryWrapper);

        // 选择题
        List<Question> type1List = questionList.stream().filter(question -> question.getType() == 1)
                .collect(Collectors.toList());

        // 判断题
        List<Question> type2List = questionList.stream().filter(question -> question.getType() == 2)
                .collect(Collectors.toList());

        // 问答题
        List<Question> type3List = questionList.stream().filter(question -> question.getType() == 3)
                .collect(Collectors.toList());

        if (type1List.size() < paperDTO.getType1()) {
            throw new ServiceException("-1", "选择题数量不足");
        }
        if (type2List.size() < paperDTO.getType2()) {
            throw new ServiceException("-1", "判断题数量不足");
        }
        if (type3List.size() < paperDTO.getType3()) {
            throw new ServiceException("-1", "问答题数量不足");
        }

        // 开始随机组卷
        List<PaperQuestion> paperQuestion = getPaperQuestion(type1List.size(), paperDTO.getType1(), type1List, paperDTO.getPaperId());
        paperQuestion.addAll(getPaperQuestion(type2List.size(), paperDTO.getType2(), type2List, paperDTO.getPaperId()));
        paperQuestion.addAll(getPaperQuestion(type3List.size(), paperDTO.getType3(), type3List, paperDTO.getPaperId()));


        paperQuestionService.saveBatch(paperQuestion);  // 批量插入关联关系表
        return Result.success();
    }

    /**
     * f封装一个获取试卷和题目关联关系list的方法
     * <p>
     * questionSize 题目总数量
     * paperQuestionSize  试卷题目的数量
     * source 题型
     */
    private List<PaperQuestion> getPaperQuestion(int questionSize, int paperQuestionSize, List<Question> source,
                                                 Integer paperId) {
        List<Integer> typeRandomList = getEleList(questionSize, paperQuestionSize);
        List<PaperQuestion> list = new ArrayList<>();

        for (Integer index : typeRandomList) {
            Question question = source.get(index);
            PaperQuestion paperQuestion = new PaperQuestion();
            paperQuestion.setPaperId(paperId);
            paperQuestion.setQuestionId(question.getId());
            list.add(paperQuestion);
        }
        return list;
    }

    /**
     * 封装一个获取随机数的方法
     * sourceSize 原始数组有多长， resultSize 获取指定长度的数组
     */
    private List<Integer> getEleList(int sourceSize, int resultSize) {
        ArrayList<Integer> list = CollUtil.newArrayList();
        for (int i = 0; i < sourceSize; i++) {
            list.add(i);
        }
        return RandomUtil.randomEleList(list, resultSize);
    }


    //查询所有数据
    @GetMapping("/view/{paperId}")
    public Result view(@PathVariable Integer paperId) {
        List<Question> list = paperQuestionService.selectQuestions(paperId);
        return Result.success(list);
    }

    //查询所有数据
    @GetMapping()
    public Result findAll() {
        return Result.success(paperService.list());
    }

    //删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(paperService.removeById(id));
    }

    //批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(paperService.removeByIds(ids));
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(paperService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {

        QueryWrapper<Paper> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        return Result.success(paperService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }
}



